<?php

class KF_Controller extends CI_Controller
{
    function __construct($auth = false)
    {
        parent::__construct();


        $this->initialization();

        if ($auth && $this->user() === false)
        {
            $this->error('请重新登录', '/login');
        }

        $this->load->database();
        $this->load->library('framework');
    }
    /**
    * 简单对称加密算法之加密
        $string 需要加密的字串
        $skey 加密EKY
    */
    public function encode($string = '', $skey = 'kfyao') {
        $strArr = str_split(base64_encode($string));
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
            $key < $strCount && $strArr[$key].=$value;
        return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
    }

    /**
    * 简单对称加密算法之加密
        $string 需要解密的字串
        $skey 解密EKY
    */
    public function decode($string = '', $skey = 'kfyao') {
        $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
            $key <= $strCount  && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
        return base64_decode(join('', $strArr));
    }


    protected function initialization()
    {
        define('IS_AJAX', !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
        define('IS_POST', $_SERVER['REQUEST_METHOD'] == 'POST');
        define('IS_GET', $_SERVER['REQUEST_METHOD'] == 'GET');
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param string $message 错误信息
     * @param string $jumpUrl 页面跳转地址
     * @param mixed $ajax 是否为Ajax方式 当数字时指定跳转时间
     * @return void
     */
    protected function error($message = '', $jumpUrl = '', $ajax = false)
    {
        $this->dispatchJump($message, 0, $jumpUrl, $ajax);
    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param string $message 提示信息
     * @param string $jumpUrl 页面跳转地址
     * @param mixed $ajax 是否为Ajax方式 当数字时指定跳转时间
     * @return void
     */
    protected function success($message = '', $jumpUrl = '', $ajax = false)
    {
        $this->dispatchJump($message, 1, $jumpUrl, $ajax);
    }

    /**
     * 默认跳转操作 支持错误导向和正确跳转
     * 调用模板显示 默认为public目录下面的success页面
     * 提示页面为可配置 支持模板标签
     * @param string $message 提示信息
     * @param Boolean $status 状态
     * @param string $jumpUrl 页面跳转地址
     * @param mixed $ajax 是否为Ajax方式 当数字时指定跳转时间
     * @access private
     * @return void
     */
    private function dispatchJump($message, $status = 1, $jumpUrl = '', $ajax = false)
    {
        if (true === $ajax || IS_AJAX)
        {// AJAX提交
            $data = is_array($ajax) ? $ajax : array();
            $data['info'] = $message;
            $data['status'] = $status;
            if ($jumpUrl)
            {
                if (is_string($jumpUrl)) $data['url'] = $jumpUrl;
                else if (is_array($jumpUrl)) $data = array_merge($jumpUrl, $data);
            }
            $this->ajaxReturn($data);
        }
        if ($ajax === false)
        {
            $this->redirect($jumpUrl);
            exit;
        }

        if (is_array($ajax))
        {
            $this->load->view('', $ajax);
        }
        else
        {
            $data = isset($this->_data) ? $this->_data : array();
            if (is_int($ajax)) $data['waitSecond'] = $ajax;
            if (!empty($jumpUrl)) $data['jumpUrl'] = $jumpUrl;
            // 提示标题
            $data['msgTitle'] = $status ? '操作成功！' : '操作失败！';
            //如果设置了关闭窗口，则提示完毕后自动关闭窗口
            if (isset($data['closeWin'])) $data['jumpUrl'] = 'javascript:window.close();';
            $data['status'] = $status;   // 状态
            if ($status)
            { //发送成功信息
                $data['message'] = $message;// 提示信息
                // 成功操作后默认停留1秒
                if (!isset($data['waitSecond'])) $data['waitSecond'] = '1';
                // 默认操作成功自动返回操作前页面
                if (!isset($data['jumpUrl'])) $data['jumpUrl'] = $_SERVER["HTTP_REFERER"];
                $this->load->view('auth/access', $data);
            }
            else
            {
                $data['error'] = $message;// 提示信息
                //发生错误时候默认停留3秒
                if (!isset($data['waitSecond'])) $data['waitSecond'] = '3';
                // 默认发生错误的话自动返回上页
                if (!isset($data['jumpUrl'])) $data['jumpUrl'] = "javascript:history.back(-1);";
                $this->load->view('public/dispatch_jump', $data);
                // 中止执行  避免出错后继续执行
            }
        }
        exit($this->output->get_output());
    }

    /**
     * Ajax方式返回数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type AJAX返回数据格式
     * @return void
     */
    protected function ajaxReturn($data, $type = 'JSON')
    {
        switch (strtoupper($type))
        {
            case 'JSON':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode($data));
            case 'XML':
                // 返回xml格式数据
                header('Content-Type:text/xml; charset=utf-8');
                exit(xml_encode($data));
            case 'JSONP':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                $handler = isset($_GET['callback']) ? $_GET['callback'] : 'jsonpReturn';
                exit($handler . '(' . json_encode($data) . ');');
            case 'EVAL':
                // 返回可执行的js脚本
                header('Content-Type:text/html; charset=utf-8');
                exit($data);
        }
    }

//    /**
//     * Ajax方式返回数据到客户端
//     * @param string $message 提示信息
//     * @param boolean $status 状态
//     * @param array $params 其他信息
//     * @return void
//     */
//    protected function ajaxReturn($message, $status = true, $params = array())
//    {
//        header('Content-Type:application/json; charset=utf-8');
//        $data = array();
//        $data['info'] = $message;
//        $data['status'] = $status;
//        $params && $data = array_merge($params, $data);
//        exit(json_encode($data));
//    }

    protected function user($key = false)
    {
        // if (isset($_SESSION['user']) && !empty($_SESSION['user']))
        // {
        //     return $key ? isset($_SESSION['user'][$key]) ? $_SESSION['user'][$key] : '' : $_SESSION['user'];
        // }
        $login_user_info = $this->decode($_COOKIE['login_user_info']);
        $login_user_info = json_decode($login_user_info,true);
        
        if (!empty($login_user_info) && time() < $login_user_info['expire'])
        {
            return $login_user_info;
        }
        return false;
    }

    /**
     * URL重定向
     * @param string $url 重定向的URL地址
     * @param integer $time 重定向的等待时间（秒）
     * @param string $msg 重定向前的提示信息
     * @return void
     */
    function redirect($url, $time = 0, $msg = '')
    {
        //多行URL地址支持
        $url = str_replace(array("\n", "\r"), '', $url);
        if (empty($msg))
            $msg = "系统将在{$time}秒之后自动跳转到{$url}！";
        if (!headers_sent())
        {
            // redirect
            if (0 === $time)
            {
                header('location: ' . $url);
            }
            else
            {
                header("refresh:{$time};url={$url}");
                echo($msg);
            }
            exit();
        }
        else
        {
            $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
            if ($time != 0) $str .= $msg;
            exit($str);
        }
    }
}

class KF_Auth_Controller extends KF_Controller
{
    protected $user_id;

    function __construct()
    {
        parent::__construct(true);

        $this->user_id = intval($this->user('uid'));

        //权限控制
        $this->load->library('authority');
        if (!$this->check('/' . $this->router->class . '/' . $this->router->method))
        {
//            show_error('111', 11, 'An Error Was Encountered');
//            $this->error('您没有权限访问此功能', '/home/index');
        }
    }

    function get_rule_list(&$rules, $pid, $level = 1)
    {
        $result = array();
        if (empty($rules)) return $result;
        foreach ($rules as $rule)
        {
            if ($rule['pid'] == $pid && $this->check($rule['name']))
            {
                $result[$rule['id']] = $rule;
                $result[$rule['id']]['level'] = $level;
                $result[$rule['id']]['items'] = $this->get_rule_list($rules, $rule['id'], $level + 1);
            }
        }
        return $result;
    }

    function check($url, $user_id = 0, $type = 1, $mode = 'url', $relation = 'or')
    {
        if ($user_id <= 0) $user_id = $this->user_id;
        if (in_array($user_id, config_item('administrator'))) return true;
        return $this->authority->check($url, $user_id, $type, $mode, $relation);
    }

    function check2($class = '')
    {
        $auth = array();
        foreach (func_get_args() as $i => $arg)
        {
            if ($i == 0) continue;
            $url = $class && strpos($arg, '/') !== 0 ? '/' . $class . '/' . $arg : $arg;
            //$key = ($pos = strrpos($arg, '/')) === false ? $arg : substr($arg, $pos + 1);
            $key = str_replace('/', '_', trim($arg, '/'));
            $auth[$key] = $this->check($url);
        }
        return $auth;
    }
}

class MenuTree
{
    /**
     * 返回多层栏目
     * @param $data 操作的数组
     * @param int $pid 一级PID的值
     * @param string $html 栏目名称前缀
     * @param string $fieldPri 唯一键名，如果是表则是表的主键
     * @param string $fieldPid 父ID键名
     * @param int $level 不需要传参数（执行时调用）
     * @return array
     */
    static public function channelLevel($data, $pid = 0, $html = "&nbsp;", $fieldPri = 'cid', $fieldPid = 'pid', $level = 1)
    {
        if (empty($data))
        {
            return array();
        }
        $arr = array();
        foreach ($data as $v)
        {
            if ($v[$fieldPid] == $pid)
            {
                $arr[$v[$fieldPri]] = $v;
                $arr[$v[$fieldPri]]['_level'] = $level;
                $arr[$v[$fieldPri]]['_html'] = str_repeat($html, $level - 1);
                $arr[$v[$fieldPri]]["_data"] = self::channelLevel($data, $v[$fieldPri], $html, $fieldPri, $fieldPid, $level + 1);
            }
        }
        return $arr;
    }

    /**
     * 获得所有子栏目
     * @param $data 栏目数据
     * @param int $pid 操作的栏目
     * @param string $html 栏目名前字符
     * @param string $fieldPri 表主键
     * @param string $fieldPid 父id
     * @param int $level 等级
     * @return array
     */
    static public function channelList($data, $pid = 0, $html = "&nbsp;", $fieldPri = 'cid', $fieldPid = 'pid', $level = 1)
    {
        $data = self::_channelList($data, $pid, $html, $fieldPri, $fieldPid, $level);
        if (empty($data))
            return $data;
        foreach ($data as $n => $m)
        {
            if ($m['_level'] == 1)
                continue;
            $data[$n]['_first'] = false;
            $data[$n]['_end'] = false;
            if (!isset($data[$n - 1]) || $data[$n - 1]['_level'] != $m['_level'])
            {
                $data[$n]['_first'] = true;
            }
            if (isset($data[$n + 1]) && $data[$n]['_level'] > $data[$n + 1]['_level'])
            {
                $data[$n]['_end'] = true;
            }
        }
        //更新key为栏目主键
        $category = array();
        foreach ($data as $d)
        {
            $category[$d[$fieldPri]] = $d;
        }
        return $category;
    }

    //只供channelList方法使用
    static private function _channelList($data, $pid = 0, $html = "&nbsp;", $fieldPri = 'cid', $fieldPid = 'pid', $level = 1)
    {
        if (empty($data))
            return array();
        $arr = array();
        foreach ($data as $v)
        {
            $id = $v[$fieldPri];
            if ($v[$fieldPid] == $pid)
            {
                $v['_level'] = $level;
                $v['_html'] = str_repeat($html, $level - 1);
                array_push($arr, $v);
                $tmp = self::_channelList($data, $id, $html, $fieldPri, $fieldPid, $level + 1);
                $arr = array_merge($arr, $tmp);
            }
        }
        return $arr;
    }

    /**
     * 获得树状数据
     * @param $data 数据
     * @param $title 字段名
     * @param string $fieldPri 主键id
     * @param string $fieldPid 父id
     * @return array
     */
    static public function tree($data, $title, $fieldPri = 'cid', $fieldPid = 'pid')
    {
        if (!is_array($data) || empty($data))
            return array();
        $arr = self::channelList($data, 0, '', $fieldPri, $fieldPid);
        foreach ($arr as $k => $v)
        {
            $str = "";
            if ($v['_level'] > 2)
            {
                for ($i = 1; $i < $v['_level'] - 1; $i++)
                {
                    $str .= "&emsp;│";
                }
            }
            if ($v['_level'] != 1)
            {
                $t = $title ? $v[$title] : "";
                if (isset($arr[$k + 1]) && $arr[$k + 1]['_level'] >= $arr[$k]['_level'])
                {
                    $arr[$k]['_name'] = $str . "&emsp;├─ " . $v['_html'] . $t;
                }
                else
                {
                    $arr[$k]['_name'] = $str . "&emsp;└─ " . $v['_html'] . $t;
                }
            }
            else
            {
                $arr[$k]['_name'] = $v[$title];
            }
        }
        //设置主键为$fieldPri
        $data = array();
        foreach ($arr as $d)
        {
            $data[$d[$fieldPri]] = $d;
        }
        return $data;
    }
}